import React, { useEffect, useState } from 'react';
import { verifyOrgIds } from '@api/asset';
import PropTypes from 'prop-types';
import { Button, Checkbox, Col, Icon, List, message, Row, Tabs, Tooltip } from 'antd';
import { Link } from 'react-router-dom';
import lodash from 'lodash';
import moment from 'moment';
import countryCodeMap from '@util/countryCodeMap';
import { withRouter } from 'react-router-dom';
import './index.less';
import '@containers/asset-manage/components/asset-content/flag.css';
import _ from 'lodash';

const prefixCls = 'asset-org-content';

const emptyText = {
  initError: '您还未进行公网资产查询设置，请点击“查询设置”，去获取企业公网的资产',
  searchError: '没有查询到相关资产，请修改查询条件！'
};

const AssetNetList = props => {
  const {
    dataSource,
    onPageChange,
    pageOpts = {},
    errorOpts = {},
    type,
    loading,
    handleVerifiedSuccess,
    navBarStyle,
    selectIds,
    handleChangeSelectIds
  } = props;
  const { page = 1, pageSize = 10, count = 0 } = pageOpts;
  const errorKey = Object.keys(errorOpts).find(item => errorOpts[item]);

  const [data, setData] = useState([]);
  // 单独记录每一页的勾选框状态
  const selectCheckAttr = `page${type}${page}`;
  const [checkAll, setCheckAll] = useState({
    [selectCheckAttr]: false
  });
  const [indeterminate, setIndeterminate] = useState({
    [selectCheckAttr]: false
  });

  const [spinning, setSpinning] = useState(false);

  //判断悬浮样式
  const fixedClassName = Object.values(navBarStyle).length ? prefixCls + '-select-fixed' : '';

  useEffect(() => {
    if (dataSource) {
      setData(
        dataSource.map(item => {
          return {
            ...item,
            checked: selectIds.includes(item._id)
          };
        })
      );
    }
  }, [dataSource]);

  const handleSelectAll = () => {
    let currentPageIds = [];
    data.forEach(item => {
      item.checked = !checkAll[selectCheckAttr];
      currentPageIds.push(item._id);
    });

    if (!checkAll[selectCheckAttr]) {
      // 如果全选，则将该页ids合并入selectIds
      handleChangeSelectIds(type, _.union(selectIds, currentPageIds));
    } else {
      // 如果取消全选，selectIds就过滤该页的ids
      handleChangeSelectIds(type, _.difference(selectIds, currentPageIds));
    }
    setCheckAll({ ...checkAll, [selectCheckAttr]: !checkAll[selectCheckAttr] });
    setIndeterminate({ ...indeterminate, [selectCheckAttr]: false });
    setData([...data]);
  };

  const handleVerified = ids => {
    setSpinning(true);
    verifyOrgIds(ids)
      .then(() => {
        message.success(`${type === 'isVerified' ? '更新' : '添加'}成功`);
        //取消全选，半选，清空选中id集合
        setCheckAll({});
        handleChangeSelectIds(type, []);
        setIndeterminate({});
        handleVerifiedSuccess();
      })
      .catch(err => {
        message.error(`${type === 'isVerified' ? '更新' : '添加'}失败` + err.message);
      })
      .finally(() => {
        setSpinning(false);
      });
  };

  const handleItemCheck = e => {
    const {
      target: { checked, value }
    } = e;
    const selectObj = data.find(item => item._id === value);
    if (selectObj) {
      selectObj.checked = checked;
    }

    // 添加或过滤选中的id
    if (checked) {
      handleChangeSelectIds(type, _.union(selectIds, [value]));
    } else {
      handleChangeSelectIds(type, _.difference(selectIds, [value]));
    }
    let checkLen = 0;
    data.forEach(item => {
      if (item.checked) {
        ++checkLen;
      }
    });
    setData([...data]);

    //手动实现全选，半选选择框
    if (checkLen === data.length) {
      setCheckAll({ ...checkAll, [selectCheckAttr]: true });
      setIndeterminate({ ...indeterminate, [selectCheckAttr]: false });
    } else if (checkLen > 0 && checkLen < data.length) {
      setCheckAll({ ...checkAll, [selectCheckAttr]: false });
      setIndeterminate({ ...indeterminate, [selectCheckAttr]: true });
    } else if (!checkLen) {
      setCheckAll({ ...checkAll, [selectCheckAttr]: false });
      setIndeterminate({ ...indeterminate, [selectCheckAttr]: false });
    }
  };

  return (
    <div className={prefixCls}>
      {errorKey ? (
        <div className={`${prefixCls}-empty`}>{loading ? '' : emptyText[errorKey]}</div>
      ) : (
        <>
          <div className={`${prefixCls}-select ${fixedClassName}`}>
            <Button
              type="primary"
              onClick={() => handleVerified(selectIds)}
              disabled={!selectIds.length}
            >
              批量{type === 'isVerified' ? '更新' : '添加'}到资产列表
            </Button>
            <div className={`${prefixCls}-select-all`}>
              <Checkbox
                onChange={handleSelectAll}
                checked={checkAll[selectCheckAttr]}
                indeterminate={indeterminate[selectCheckAttr]}
                disabled={!data.length}
              >
                选择本页
              </Checkbox>
            </div>
          </div>
          <List
            size="large"
            loading={loading || spinning}
            pagination={{
              onChange: (page, pageSize) => {
                onPageChange(page, pageSize, type);
              },
              current: page,
              pageSize: pageSize,
              total: count,
              showSizeChanger: true,
              showQuickJumper: true,
              pageSizeOptions: ['5', '10', '15', '20'],
              onShowSizeChange: (page, pageSize) => {
                onPageChange(page, pageSize, type);
              }
            }}
            dataSource={data}
            className={`${prefixCls}-list`}
            renderItem={item => {
              const country = lodash.get(item, 'geoInfo.country.nameCN', '');
              //获取国旗
              const countryMapElement =
                country && countryCodeMap[country] ? (
                  <i
                    className={`flag flag-${countryCodeMap[country]}`}
                    style={{ marginRight: '4px' }}
                  />
                ) : null;

              //根据类型获取banner
              const banner =
                item.type === 'host'
                  ? item.banner
                  : lodash.get(item, 'webParams.header', '') +
                    lodash.get(item, 'webParams.rawData', '');

              const ssl = lodash.get(item, 'portInfo.ssl', '');

              //根据类型获取ip或域名
              let ipInfo =
                lodash.get(item, 'type') === 'host'
                  ? lodash.get(item, 'ip', [])[0]
                  : lodash.get(item, 'target');

              ipInfo = ipInfo || '';

              //判断是否跳转
              const needJump = ['http', 'https'].includes(_.get(item, 'portInfo.service'));

              //跳转链接
              let url = '';
              if (needJump) {
                url =
                  lodash.get(item, 'type') === 'web'
                    ? `${_.get(item, 'portInfo.service')}://${lodash.get(item, 'target')}`
                    : `${_.get(item, 'portInfo.service')}://${
                        lodash.get(item, 'ip', [])[0]
                      }:${_.get(item, 'portInfo.port')}`;
              }
              const title = lodash.get(item, 'title', '');

              return (
                <List.Item key={item._id}>
                  <Row className={`${prefixCls}-list-row`}>
                    <Col span={1} className={`${prefixCls}-list-row-checkbox`}>
                      <Checkbox
                        value={item._id}
                        checked={item.checked}
                        onChange={handleItemCheck}
                      />
                    </Col>
                    <Col span={5} className={`${prefixCls}-list-row-info`}>
                      <h3 className={`${prefixCls}-list-row-info-ip`}>
                        <Link
                          style={{ color: 'black' }}
                          to={`/asset-config/asset-org-manage/${item._id}`}
                        >
                          {ipInfo.length > 24 ? <Tooltip title={ipInfo}>{ipInfo}</Tooltip> : ipInfo}
                        </Link>
                        {needJump && (
                          <Icon
                            theme="filled"
                            type="right-circle"
                            style={{ marginLeft: '5px' }}
                            onClick={() => window.open(url, '_blank')}
                          />
                        )}
                      </h3>
                      <div className={`${prefixCls}-list-row-info-port`}>
                        {lodash.get(item, 'portInfo.port', '')}
                        {lodash.get(item, 'portInfo.service') ? '/' : ''}
                        {lodash.get(item, 'portInfo.service', '')}
                      </div>
                      <div className={`${prefixCls}-list-row-info-geography`}>
                        {countryMapElement}
                        {country}
                        {lodash.get(item, 'geoInfo.city.nameCN') ? ',' : ''}
                        {lodash.get(item, 'geoInfo.city.nameCN', '')}
                      </div>
                      <div className={`${prefixCls}-list-row-info-time`}>
                        {moment(item.timestamp || '').format('YYYY-MM-DD HH:mm')}
                      </div>
                      <div className={`${prefixCls}-list-row-info-isp`}>
                        {lodash.get(item, 'geoInfo.isp', '')}
                      </div>
                      <div className={`${prefixCls}-list-row-info-asn`}>
                        <span>{lodash.get(item, 'geoInfo.asn') ? 'ASN:' : ''}</span>
                        {lodash.get(item, 'geoInfo.asn', '')}
                      </div>
                      <div className={`${prefixCls}-list-row-info-title`}>
                        <span>{lodash.get(item, 'title') ? 'TITLE:' : ''}</span>
                        <Tooltip title={title}>{title}</Tooltip>
                      </div>
                    </Col>
                    <Col span={13}>
                      <Tabs>
                        <Tabs.TabPane tab="Banner" key={`${item._id}-banner`}>
                          <div className={`${prefixCls}-list-row-banner`}>{banner}</div>
                        </Tabs.TabPane>
                        {ssl && (
                          <Tabs.TabPane tab="证书" key={`${item._id}-ssl`}>
                            <div className={`${prefixCls}-list-row-banner`}>{ssl}</div>
                          </Tabs.TabPane>
                        )}
                      </Tabs>
                    </Col>
                    <Col span={5} className={`${prefixCls}-list-row-action`}>
                      <Button key="add" type="link" onClick={() => handleVerified([item._id])}>
                        {type === 'isVerified' ? '更新' : '添加'}到资产列表
                      </Button>
                    </Col>
                  </Row>
                </List.Item>
              );
            }}
          />
        </>
      )}
    </div>
  );
};

AssetNetList.propTypes = {
  onPageChange: PropTypes.func,
  handleVerifiedSuccess: PropTypes.func,
  history: PropTypes.object,
  dataSource: PropTypes.array,
  pageOpts: PropTypes.object,
  type: PropTypes.string,
  loading: PropTypes.bool,
  errorOpts: PropTypes.object,
  navBarStyle: PropTypes.object,
  selectIds: PropTypes.array,
  handleChangeSelectIds: PropTypes.func
};

export default withRouter(AssetNetList);
